"use client"

import React, { createContext, useContext, useState } from 'react'
import { AlertTriangle, X } from 'lucide-react'
import { Button } from './button'
import { Input } from './input'

// 输入对话框配置
export interface PromptOptions {
  title?: string
  message: string
  defaultValue?: string
  placeholder?: string
  confirmText?: string
  cancelText?: string
  type?: 'password' | 'text'
  onConfirm?: (value: string) => void | Promise<void>
  onCancel?: () => void
}

// Prompt Context
interface PromptContextType {
  prompt: (options: PromptOptions) => Promise<string | null>
}

const PromptContext = createContext<PromptContextType | null>(null)

// Prompt Provider组件
export function PromptProvider({ children }: { children: React.ReactNode }) {
  const [isOpen, setIsOpen] = useState(false)
  const [options, setOptions] = useState<PromptOptions | null>(null)
  const [inputValue, setInputValue] = useState('')
  const [resolvePromise, setResolvePromise] = useState<((value: string | null) => void) | null>(null)

  const prompt = (options: PromptOptions): Promise<string | null> => {
    return new Promise((resolve) => {
      setOptions(options)
      setInputValue(options.defaultValue || '')
      setResolvePromise(() => resolve)
      setIsOpen(true)
    })
  }

  const handleConfirm = async () => {
    setIsOpen(false)
    if (options?.onConfirm) {
      try {
        await options.onConfirm(inputValue)
      } catch (error) {
        console.error('Prompt action failed:', error)
      }
    }
    if (resolvePromise) {
      resolvePromise(inputValue)
    }
    setOptions(null)
    setResolvePromise(null)
    setInputValue('')
  }

  const handleCancel = () => {
    setIsOpen(false)
    if (options?.onCancel) {
      options.onCancel()
    }
    if (resolvePromise) {
      resolvePromise(null)
    }
    setOptions(null)
    setResolvePromise(null)
    setInputValue('')
  }

  return (
    <PromptContext.Provider value={{ prompt }}>
      {children}
      <PromptDialog
        isOpen={isOpen}
        options={options}
        inputValue={inputValue}
        setInputValue={setInputValue}
        onConfirm={handleConfirm}
        onCancel={handleCancel}
      />
    </PromptContext.Provider>
  )
}

// usePrompt hook
export function usePrompt() {
  const context = useContext(PromptContext)
  if (!context) {
    throw new Error('usePrompt must be used within a PromptProvider')
  }
  return context.prompt
}

// 输入对话框组件
interface PromptDialogProps {
  isOpen: boolean
  options: PromptOptions | null
  inputValue: string
  setInputValue: (value: string) => void
  onConfirm: () => void
  onCancel: () => void
}

function PromptDialog({ isOpen, options, inputValue, setInputValue, onConfirm, onCancel }: PromptDialogProps) {
  if (!isOpen || !options) return null

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      onConfirm()
    } else if (e.key === 'Escape') {
      onCancel()
    }
  }

  return (
    <div className="fixed inset-0 z-50 overflow-y-auto">
      {/* 背景遮罩 */}
      <div className="fixed inset-0 bg-black bg-opacity-50 transition-opacity" onClick={onCancel} />
      
      {/* 对话框容器 */}
      <div className="flex min-h-full items-center justify-center p-4">
        <div className="relative transform overflow-hidden rounded-lg bg-white shadow-xl transition-all sm:w-full sm:max-w-lg">
          {/* 关闭按钮 */}
          <button
            onClick={onCancel}
            className="absolute right-4 top-4 text-gray-400 hover:text-gray-600 focus:outline-none"
          >
            <X className="h-5 w-5" />
          </button>

          {/* 内容区域 */}
          <div className="px-6 py-6">
            <div className="flex items-start space-x-4">
              {/* 图标 */}
              <div className="flex-shrink-0 flex items-center justify-center w-12 h-12 rounded-full bg-blue-100">
                <AlertTriangle className="h-6 w-6 text-blue-600" />
              </div>

              {/* 文本内容和输入框 */}
              <div className="flex-1 mt-1">
                {options.title && (
                  <h3 className="text-lg font-medium text-gray-900 mb-2">
                    {options.title}
                  </h3>
                )}
                <p className="text-sm text-gray-600 mb-4">
                  {options.message}
                </p>
                
                {/* 输入框 */}
                <Input
                  type={options.type || 'text'}
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  placeholder={options.placeholder}
                  onKeyDown={handleKeyPress}
                  autoFocus
                  className="w-full"
                />
              </div>
            </div>
          </div>

          {/* 按钮区域 */}
          <div className="bg-gray-50 px-6 py-4 flex justify-end space-x-3">
            <Button
              variant="outline"
              onClick={onCancel}
            >
              {options.cancelText || '取消'}
            </Button>
            <Button
              className="bg-blue-600 hover:bg-blue-700 focus:ring-blue-500 text-white focus:ring-2 focus:ring-offset-2"
              onClick={onConfirm}
              disabled={!inputValue.trim()}
            >
              {options.confirmText || '确认'}
            </Button>
          </div>
        </div>
      </div>
    </div>
  )
}